/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 */

import path from 'path';

import { InputFile, MetricLogType, OutputFile, SubmitOption, TaskState } from '@ohos/hvigor';

import { OhosLogger } from '../utils/log/ohos-logger.js';
import { AbstractNativeStrip } from './abstract/abstract-native-strip.js';
import { TaskNames } from './common/task-names.js';
import { DoNativeStrip } from './do-native-strip.js';
import { TargetTaskService } from './service/target-task-service.js';
import { cacheNativeLibs } from './worker/cache-libs.js';

/**
 * build-native-strip任务执行完执行这个任务把本次的strip结果落盘保存
 */
export class CacheNativeLibs extends AbstractNativeStrip {
  private logger: OhosLogger = OhosLogger.getLogger(CacheNativeLibs.name);
  @InputFile({ isDirectory: true }) private get cacheStrippedNativeLibs(): string {
    return this.strippedNativeLibs;
  }
  @OutputFile({ isDirectory: false }) private get buildCacheFilePath(): string {
    return this.cacheFilePath;
  }

  constructor(targetService: TargetTaskService) {
    super(targetService, TaskNames.Task.CACHE_NATIVE_LIBS);
  }

  protected async doTaskAction(): Promise<void> {
    const script: string = path.resolve(__dirname, './worker/cache-libs.js/cacheNativeLibs');
    const options: SubmitOption = {
      workInput: {
        intermediatesProcessLibs: this.intermediatesProcessLibs,
        strippedNativeLibs: this.cacheStrippedNativeLibs,
        cacheFilePath: this.buildCacheFilePath,
        debugSymbol: this.debugSymbol,
      },
    };
    if (this.getWorkerPool().submit(this, script, options).getState() === TaskState.REJECT) {
      const executeTaskName = 'cache native libs';
      const subExecuteDurationEvent = this.durationEvent.createSubEvent(executeTaskName, '');
      subExecuteDurationEvent.start();
      this.logger.debug('Worker dispatch failed, running cacheNativeLibs on main thread.');
      await cacheNativeLibs(options.workInput);
      subExecuteDurationEvent.stop();
      subExecuteDurationEvent.setLog(executeTaskName, MetricLogType.INFO);
    }
  }

  initTaskDepends(): void {
    this.declareDepends(DoNativeStrip.name);
  }
}
